package com.pishou.player;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.SurfaceTexture;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.os.Process;
import android.util.Base64;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.TextureView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pishou.Data;
import com.pishou.ParamConfig;
import com.pishou.URLConfig;
import com.pishou.code.bean.Comment;
import com.pishou.shop.DetailActivity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;


public class ComentVideoActivity extends Activity implements TextureView.SurfaceTextureListener {

    private IjkMediaPlayer mp;
    private TextureView tv;
    private Surface surface;
    private LinearLayout ll_comment_image;
    private TextView tv_comment_content;

    private Float rotation = 0.0f;

    private String[] videoPaths;
    private Integer current;

    private float x1;
    private float y1;

    private String type_reduce = "REDUCR";
    private String type_add = "ADD";

    private String nextType_Manual = "Manual";
    private String nextType_Auto = "Auto";
    private String next;
    private Integer auto_current_record;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comentvideo);

        Intent intent = getIntent();
        videoPaths = intent.getStringArrayExtra("videoPaths");
        current = intent.getIntExtra("current",0);

        tv = findViewById(R.id.tv_commentVideo);
        tv.setSurfaceTextureListener(this);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        ll_comment_image = findViewById(R.id.ll_show_comment_image);
        tv_comment_content = findViewById(R.id.tv_comment_content);

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == 0){
            x1 = ev.getX();
            y1 = ev.getY();
        }else if(ev.getAction() == 1){
            float diffX = Math.abs(x1 - ev.getX());
            float diffY = Math.abs(y1 - ev.getY());
            if (diffX > diffY && diffX > 100){      // X的差值比Y大，判断用户为左右滑动,滑动距离大于100个像素
                if (videoPaths.length > 1 ){        // 播放列表中，视频数大于1个，有切换视频空间
                    if (x1 > ev.getX()){            // x1为起点，起点较大，终点较小，判断用户为向左滑动，播放上一个视频，反之则为向右滑动，播放下一个视频
                        changeCurrent(type_reduce);
                    }else{
                        changeCurrent(type_add);
                    }
                }
                if (mp != null && mp.isPlaying()){  // 播放下一个视频
                    mp.stop();
                    mp.reset();
                    mp.release();
                    next = nextType_Manual;
                    auto_current_record = null;
                    new PlayVideo().start();
                }
            }
            // Y的差值比X的大，判断用户为上下滑动，滑动距离大于100个像素
            else if(diffY > diffX && diffY > 100){
                finish();
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onStop() {
        if (mp!=null){
            mp.stop();
            mp.release();
        }
        super.onStop();
    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
        surface = new Surface(surfaceTexture);
        new PlayVideo().start();
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {

    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
        surfaceTexture = null;
        surface = null;
        return true;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {

    }

    private class PlayVideo extends  Thread{
        @Override
        public void run() {
            //getPlayTime(videoPaths[current]);
            Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO);
            try{
                mp = new IjkMediaPlayer();
                mp.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", 1);
                mp.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "videotoolbox", 1);
                mp.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "allowed_media_types", "video"); //根据媒体类型来配置
                mp.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", 20000);
                mp.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "buffer_size", 1048576);
                mp.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "infbuf", 0);  // 无限读
                mp.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzemaxduration", 1000L);
                mp.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "flush_packets", 1L);
                //  关闭播放器缓冲，这个必须关闭，否则会出现播放一段时间后，一直卡主，控制台打印 FFP_MSG_BUFFERING_START
                mp.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", 0L);
                mp.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", 1L);

                mp.setDataSource(videoPaths[current]);
                mp.prepareAsync();
                mp.setSurface(surface);
                mp.setOnPreparedListener(new IMediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(IMediaPlayer iMediaPlayer) {
                        tv.setRotation(Data.current_product_comment_video.get(current).getRotation());
                        mp.start();
                    }
                });
                mp.setOnCompletionListener(new IMediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(IMediaPlayer iMediaPlayer) {
                        changeCurrent(type_add);
                        if (nextType_Auto.equals(next) && current.equals(auto_current_record)){
                            finish();
                            return;
                        }
                        if(nextType_Manual.equals(next) || next == null){
                            next = nextType_Auto;
                            auto_current_record = current;
                        }
                        mp.stop();
                        mp.reset();
                        mp.release();
                        new PlayVideo().start();
                    }
                });
            }catch (Exception e){
                e.printStackTrace();
            }
            changeComment();
            super.run();
        }
    }

    /**
     * 设置图片
     * @param iv
     * @param path
     */
    private synchronized void setImage(final ImageView iv,  final String path, final Boolean scal_flag, final Integer width, final Integer height) {
        new Thread(){
            @Override
            public void run() {
                File file = new File(getCacheDir(), Base64.encodeToString(path.getBytes(),Base64.DEFAULT));
                if (!file.exists()){
                    try {
                        URL url = new URL(path);
                        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                        conn.setRequestMethod("GET");
                        conn.setConnectTimeout(5000);
                        int code = conn.getResponseCode();
                        if (code == 200){
                            InputStream in = conn.getInputStream();
                            int len = -1;
                            byte[] buffer = new byte[1024];
                            FileOutputStream fos = new FileOutputStream(file);
                            while ((len = in.read(buffer))!=-1) {
                                fos.write(buffer, 0, len);
                            }
                            fos.close();
                            in.close();
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                if (iv!=null){
                    if (scal_flag){
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inJustDecodeBounds = true;
                        BitmapFactory.decodeFile(file.getAbsolutePath(),options);
                        int w = options.outWidth;
                        int h = options.outHeight;
                        // 计算缩放比
                        int scalX = 0;
                        if (width != null && width != 0){
                            scalX = w/width;
                        }
                        int scalY = h/height;
                        int scal = 1;
                        // 计算宽和高的缩放比，选择缩放比较大的使用
                        if (scalX>scalY && scalX>scal) {
                            scal = scalX;
                        }
                        if (scalY > scalX && scalY > scal) {
                            scal = scalY;
                        }
                        options.inSampleSize = scal;
                        // 取消不读取图片的设置，并且携带缩放比读取图片
                        options.inJustDecodeBounds = false;
                        final Bitmap cacheBitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                iv.setImageBitmap(cacheBitmap);
                            }
                        });
                    }else{
                        final Bitmap cacheBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                iv.setImageBitmap(cacheBitmap);
                            }
                        });
                    }
                }
                super.run();
            }
        }.start();
    }

    private void changeComment(){
        final Comment comment = DetailActivity.product.getVideo_comment().get(current);
        for (int i = 0 ;i < comment.getPicture();i++){
            ImageView image = (ImageView)ll_comment_image.getChildAt(i);
            setImage(image, URLConfig.oss_host+"comment/"+(i+1)+"/"+comment.getId()+".jpg",true,500,700);
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv_comment_content.setText(comment.getContent());
            }
        });
    }

    private void changeCurrent(String type){
        if (type.equals(type_reduce)){
            current--;
            if (current < 0){           // 游标超过左边范围，设置为右边起始点
                current = videoPaths.length - 1;
            }
        }else if(type.equals(type_add)){
            current++;
            if (current >= videoPaths.length){  // 游标超过右边范围，设置为左边起始点
                current = 0;
            }
        }
    }
}
